-module(info2).
-export([infomanager/1]).

-include_lib("stdlib/include/qlc.hrl").

-auth("zhangyuchi@gmail.com").
-vsn("0.1").

-record(user, {id,message}).
-record(term, {id,message}).
-record(store,{id,message}).
-record(disp, {id,message}).

infomanager(init) ->
    case mnesia:create_schema([node()]) of
	ok ->
	    mnesia:start(),
	    mnesia:create_table(user,[{attributes, record_info(fields,user)},{disc_copies,[node()]}]),
	    mnesia:create_table(term,[{attributes, record_info(fields,term)},{disc_copies,[node()]}]),
	    mnesia:create_table(store,[{attributes, record_info(fields,store)},{disc_copies,[node()]}]),
    	    mnesia:create_table(disp,[{attributes, record_info(fields,disp)},{disc_copies,[node()]}]);
	Error ->
	    mnesia:start(),
	    Error
    end,
    
    infomanager(service);
infomanager(service) ->
    receive 
	{_Pid,TableName,insert,Key,Value} ->
	    _Ret = insert(TableName,Key,Value),
	    %Pid ! Ret,
	    infomanager(service);
	{Pid,TableName,lookup,Key} ->
	    Ret = lookup(TableName,Key),
	    Pid ! Ret,
	    infomanager(service);
	{_Pid,TableName,delete,Key} ->
            _Ret = delete(TableName,Key),
            infomanager(service);
	_Other ->
	    io:format("info service recv unknown msg~n"),
	    infomanager(service)
    after 120000 ->
	    infomanager(sync),
	    infomanager(service)    
    end;
infomanager(stop) ->
    mnesia:stop();
infomanager(sync) ->
    ok.
    
doquery(Q) ->
    F = fun() -> qlc:e(Q) end,
    {atomic, Val} = mnesia:transaction(F),
    Val.

lookup(user,Key) ->
    case doquery(qlc:q([X#user.message || X <- mnesia:table(user), X#user.id =:= Key ])) of
	[] ->
	    {lookup,error,null};
	[Bin] ->
            {lookup,ok,Bin};
	_ ->
	    {lookup,error,exception}
    end.

insert(user,Key,Value) ->
    Row  =  #user{id=Key, message=Value},
    F  =  fun()  ->
		  mnesia:write(Row)
	  end,
    mnesia:transaction(F),
    {insert,ok}.

delete(TableName,Key) ->
    Oid  =  {TableName, Key},
    F  =  fun()  ->
		  mnesia:delete(Oid)
	  end,
    mnesia:transaction(F),
    {delete,ok}.

